<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="用户" prop="userId">
            <UserSearch title="用户搜索" :params="{status:'0'}" :dataText="pd.queryParams.userName" @ok="searchUser1($event)" />
          </el-form-item>
          <el-form-item label="更新时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeUpdateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['demo:example1:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['demo:example1:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['demo:example1:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:example1:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.example1List" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="名称" align="center" prop="name">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['hrp:example1:edit']">
              {{ scope.row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="用户" align="center" prop="userName" />
        <el-table-column label="用户id" align="center" prop="userId" />
        <el-table-column label="创建部门" align="center" prop="deptName" />
        <el-table-column label="排序号" align="center" prop="sort" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:example1:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['demo:example1:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="pd.total>0"
        :total="pd.total"
        v-model:page="pd.queryParams.pageNum"
        v-model:limit="pd.queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改样例单表1对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="example1FormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="pd.form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="pd.form.status" placeholder="请选择状态">
            <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <UserSearch title="用户搜索" :params="{status:'0'}" :dataText="pd.form.userName" @ok="searchUser2($event)" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input v-model="pd.form.sort" placeholder="请输入排序号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Example1" lang="ts">
import {Example1VO, listExample1, getExample1, delExample1, addExample1, updateExample1 } from '@/views/demo/example1/api';
import UserSearch from '@/views/system/user/search.vue';
import {UserVO} from '@/api/system/user/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_status } = toRefs<any>(proxy?.useDict('sys_status'));
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const example1FormRef = ref<ElFormInstance>();
const pd = reactive({
  example1List: <Example1VO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <Example1VO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <Example1VO>{},
  queryParams: <Example1VO>{
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    userId: undefined,
    userName: undefined,
    params: {
      updateTime: undefined,
    }
  },
  rules: <ElFormRules>{
    name: [      { required: true, message: "名称不能为空", trigger: "blur" }    ],
    status: [      { required: true, message: "状态不能为空", trigger: "change" }    ],
    userId: [      { required: true, message: "用户不能为空", trigger: "blur" }    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

function searchUser1(vo:UserVO[]) {
  vo.forEach((v, i, a) => {
    pd.queryParams.userId = v.userId;
    return;
  });
}
function searchUser2(vo:UserVO[]) {
  vo.forEach((v, i, a) => {
    pd.form.userId = v.userId;
    return;
  });
}

/** 查询样例单表1列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listExample1(pd.queryParams);
  pd.example1List = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {};
  example1FormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Example1VO[]) {
  pd.ids = selection.map(item => item.id);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加样例单表1";
}

/** 修改按钮操作 */
async function handleUpdate(row?: Example1VO) {
  reset();
  const _id = row?.id || pd.ids[0];
  const res = await getExample1(_id);
  Object.assign(pd.form, res.data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改样例单表1";
}

/** 提交按钮 */
function submitForm() {
  example1FormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateExample1(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addExample1(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: Example1VO) {
  const _ids = row?.id || pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除样例单表1编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delExample1(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('demo/example1/export',
    {...pd.queryParams  },
    `example1_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
